package com.eas.task.imports.datasource;

import java.text.MessageFormat;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;

public class DsFactory {

    public static DataSource create(DsConfig config) {
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(config.getDriverName());
        ds.setUrl(MessageFormat.format(
                config.getUrl(),
                new Object[] { config.getHost(), config.getPort(),
                        StringUtils.trimToEmpty(config.getDbName()) }));
        ds.setUsername(config.getUserName());
        ds.setPassword(config.getPassword());
        try {
            JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
            jdbcTemplate.queryForInt("select 1 from dual");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return ds;
    }

    public static void destory(DataSource ds) {
        if (ds != null) {
            try {
                BasicDataSource dbcp = (BasicDataSource) ds;
                dbcp.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
